package modes

import "fmt"

/*
 * 描述: 直播课次表(含回放)
 *
 *****************************/
type NewLiveClass struct {
	Id           int64  `json:"live_id" xorm:"id"`                     // id
	PPId         int64  `json:"live_pid" xorm:"pid"`                   // 项目id
	SSId         int64  `json:"live_sid" xorm:"sid"`                   // 科目id [遗留]
	SId          int64  `json:"live_s_id" xorm:"s_id"`                 // 课程id [新增]
	TypeId       int64  `json:"live_type_id" xorm:"type_id"`           // 直播课程类型 [遗留]
	Courseware   string `json:"live_courseware" xorm:"courseware"`     // 课件名称(课次名称) [遗留]
	Descl        string `json:"live_desc" xorm:"descl"`                // 描述 [遗留]
	LAt          int64  `json:"live_lat" xorm:"lat"`                   // 直播时间
	EAt          int64  `json:"live_eat" xorm:"eat"`                   // 直播结束
	Clienturl    string `json:"live_clienturl" xorm:"clienturl"`       // 授课链接
	Assistanturl string `json:"live_assistanturl" xorm:"assistanturl"` // 助教链接
	ViewUrl      string `json:"live_viewurl" xorm:"viewurl"`           // 学员链接
	Instructor   string `json:"live_instructor" xorm:"instructor"`     // 授课老师
	States       int64  `json:"live_states" xorm:"states"`             // 状态  0 未开始  1 直播中  2 回放生成中(新增) 4 回放
	RevideoId    string `json:"live_revideo_id" xorm:"revideo_id"`     // 回放视频Id [新增]
	Duration     int32  `json:"live_duration" xorm:"duration"`         // 回放视频的时长(秒) [新增]
	Public       int32  `json:"live_public" xorm:"public"`             // 直播公开类型(1-非公开, 2-公开) [新增]
	PublicBack   int32  `json:"live_public_back" xorm:"public_back"`   // 回放公开类型(1-非公开, 2-公开) [新增]
	Sort         int32  `json:"live_sort" xorm:"sort"`                 // 排序(改造点: 程序步进值:100) [新增]
	At           int64  `json:"live_at" xorm:"at"`                     //创建时间
	Years        int64  `json:"years" xorm:"-"`                        //年份
	ClaUrl       string `json:"cla_url" xorm:"-"`                      //课程描述

	Rect   []RecordAt `json:"rect" xorm:"-"`    // 该课次最后最后一次播放进度
	IsMsg  int        `json:"is_msg" xorm:"-"`  // 是否已预约 1已预约 2未预约
	IsColl int        `json:"is_coll" xorm:"-"` // 是否已收藏 1已收藏 2未收藏

}

func (this *NewLiveClass) TableName() string {
	return "liveclass"
}
func (this *NewLiveClass) Load() (bool, error) {
	return Db(0).Get(this)
}
func (this *NewLiveClass) Create() (int64, error) {
	return Db(0).Insert(this)
}
func (this *NewLiveClass) Update(id int64, columns ...string) (int64, error) {
	return Db(0).ID(id).MustCols(columns...).Update(this)
}
func (this *NewLiveClass) Delete(id int64) (int64, error) {
	return Db(0).ID(id).Delete(&LiveClass{})
}

func (this *NewLiveClass) update(where string, field string) (int64, error) {
	return Db(1).Where(where).Cols(field).Update(this)
}

func (this *NewLiveClass) IdSet(field string) (int64, error) {
	where := fmt.Sprintf("id = %d", this.Id)
	return this.update(where, field)
}

func (this *NewLiveClass) LiveClassCount(sid int64) (int64, []string, error) {
	swhere := fmt.Sprintf("s_id = %d ", sid)
	cou, _ := Db(0).Where(swhere).Count(this)
	list, err := this.LiveClassName(sid)
	fmt.Println(list)
	return cou, list, err
}

func (this *NewLiveClass) LiveClassName(sid int64) ([]string, error) {
	swhere := fmt.Sprintf("s_id = %d ", sid)
	dl := []string{}
	return dl, Db(0).Table("liveclass").Cols("instructor").Where(swhere).Limit(3).Find(&dl)
}

func (this *NewLiveClass) Lookups(uid, sid int64, val *Pager) error {
	list := make([]NewLiveOrdereds, 0)
	val.TName = "liveclass"
	val.Page--
	var field, sort string
	switch val.Coll {
	case 0:
		field = fmt.Sprintf("%s.at", val.TName) // 排序
	default:
		field = fmt.Sprintf("%s.at", val.TName) // 排序
	}
	if 1 == val.Rules {
		sort = fmt.Sprintf("%s asc", field)
	} else {
		sort = fmt.Sprintf("%s desc", field)
	}
	swhere := fmt.Sprintf("s_id = %d and  states >=  2", sid)
	val.Total, _ = Db(0).Table(val.TName).Where(swhere).Count(this)
	err := Db(0).Table(val.TName).
		Where(swhere).
		OrderBy(sort).
		Limit(val.Count, val.Page*val.Count).
		Find(&list)
	collen := Collen{
		UId: uid,
	}
	collenList, err := collen.ListByUid()

	scIds := make([]int64, 0, len(list))
	kIds := make([]int64, 0, len(list))
	for s, _ := range list {
		kIds = append(kIds, list[s].SId)
	}
	//kid, _ := (&PlaySub{}).PlaySubjects(kIds)
	//for _, it := range kid {
	//	for n, _ := range list {
	//		if list[n].SId == it.Id {
	//			list[n].Years = it.Year
	//			list[n].ClaUrl = it.ClassUrl
	//		}
	//	}
	//}
	plys, _ := (&Subjects{}).ReClassName(kIds)
	for _, it := range plys {
		for n, _ := range list {
			if list[n].SId == it.SId {
				list[n].SaId = it.SId
				list[n].SName = it.SName
				list[n].ClaUrl = it.ClaUrls
				list[n].Years = int64(it.Yest)
			}
		}
	}

	mapps := map[int64]*NewLiveClass{}
	for n, _ := range list {
		scIds = append(scIds, list[n].Id)
		mapps[list[n].Id] = &list[n].NewLiveClass
	}
	rects, err := (&Records{}).RecordTime_(uid, sid, scIds)
	if err != nil {
		return err
	}
	for n, _ := range rects {
		mapps[rects[n].Id].Rect = []RecordAt{rects[n]}
	}
	if err == nil {
		val.List = list
		for i, row := range list {
			//var rec Records
			//list[i].Rect, _ = rec.RecordTime(uid, row.Id, row.SId)
			list[i].IsColl = 2
			for _, v := range collenList {
				if v.SId == row.Id && v.Type == 2 {
					list[i].IsColl = 1
				}
			}

		}
		val.List = list
	}
	return err

}

func (this *NewLiveClass) LookupsNotice(uid int64, sid int64, val *Pager) error {
	list := make([]NewLiveClass, 0)
	val.TName = "liveclass"
	val.Page--
	var field, sort string
	switch val.Coll {
	case 0:
		field = fmt.Sprintf("%s.lat", val.TName) // 排序
	default:
		field = fmt.Sprintf("%s.lat", val.TName) // 排序
	}
	//if 1 == val.Rules {
		sort = fmt.Sprintf("%s asc", field)
	//} else {
	//	sort = fmt.Sprintf("%s desc", field)
	//}
	swhere := fmt.Sprintf("s_id = %d and states < 2 ", sid)
	val.Total, _ = Db(0).Table(val.TName).Where(swhere).Count(this)
	err := Db(0).Table(val.TName).
		Where(swhere).
		OrderBy(sort).
		Limit(val.Count, val.Page*val.Count).
		Find(&list)
	plays := []int64{}
	for n, _ := range list {
		plays = append(plays, list[n].SId)
	}
	// 从上面的 list 中 提取 课程Ids 通过in语句得到所有课程的名称
	//plys, _ := (&YesSName{}).ReClassName(plays)
	var yes Subjects
	plys, _ := yes.ReClassName(plays)
	for _, it := range plys {
		for n, _ := range list {
			if list[n].SId == it.SId {
				//fmt.Println(it.ClaUrls,"it.ClaUrls")
				list[n].ClaUrl = it.ClaUrls
			}
		}
	}
	toOrder := ToOrder{
		UId: uid,
	}

	yuyueIdList, _ := toOrder.MyYuyueIdList()
	if err == nil {
		for i, _ := range list {
			// 是否预约
			list[i].IsMsg = 2
			for _, v := range yuyueIdList {
				if v == list[i].Id {
					list[i].IsMsg = 1
				}
			}
		}
		val.List = list
	}
	return err
}

type NewLiveOrdered struct {
	NewLiveClass `xorm:"extends"`
	SName        []QSName  `json:"s_name" xorm:"-"`  //课程名称
	SSName       []QSSName `json:"ss_name" xorm:"-"` //科目名称
}

type NeveOrdered struct {
	NewLiveClass `xorm:"extends"`
	SName        []QSName  `json:"s_name" xorm:"-"`  //课程名称
	SSName       []QSSName `json:"ss_name" xorm:"-"` //科目名称
}

func (this *NewLiveOrdereds) LookNotice(uid int64, sid []int64, val *Pager) error {
	list := make([]NewLiveOrdereds, 0)
	val.TName = "liveclass"
	val.Page--
	var field, sort string
	switch val.Coll {
	case 0:
		field = fmt.Sprintf("%s.lat", val.TName) // 排序
	default:
		field = fmt.Sprintf("%s.lat", val.TName) // 排序
	}
	//if 1 == val.Rules {
	sort = fmt.Sprintf("%s asc", field)
	//} else {
	//	sort = fmt.Sprintf("%s desc", field)
	//}
	swhere := fmt.Sprintf("states < 2 ")
	val.Total, _ = Db(0).Table(val.TName).In("s_id", sid).Where(swhere).Where(val.ToWhere()).Count(this)
	err := Db(0).Table(val.TName).
		In("s_id", sid).
		Where(swhere).
		Where(val.ToWhere()).
		OrderBy(sort).
		Limit(val.Count, val.Page*val.Count).
		Find(&list)
	toOrder := ToOrder{
		UId: uid,
	}
	yuyueIdList, _ := toOrder.MyYuyueIdList()
	if err == nil {
		val.List = list
		for i, _ := range list {
			//var sus Subjects
			//list[i].SName, _ = sus.RecordClassName(row.SId)
			//list[i].SSName, _ = sus.RecordClassNName(row.SId)
			// 是否预约
			list[i].IsMsg = 2
			for _, v := range yuyueIdList {
				if v == list[i].Id {
					list[i].IsMsg = 1
				}
			}
		}
		val.List = list
	}
	// 这是课次的 list ， 取得 这些 课次的 课程名称 和 科目名称
	plays := []int64{}
	for n, _ := range list {
		plays = append(plays, list[n].NewLiveClass.SId)
	}
	// 从上面的 list 中 提取 课程Ids 通过in语句得到所有课程的名称
	//plys, _ := (&YesSName{}).ReClassName(plays)
	var yes Subjects
	plys, _ := yes.ReClassName(plays)
	for _, it := range plys {
		for n, _ := range list {
			if list[n].SId == it.SId {
				list[n].SaId = it.SId
				list[n].SName = it.SName
				list[n].NewLiveClass.Years = int64(it.Yest)
				//fmt.Println(it.ClaUrls,"it.ClaUrls")
				list[n].NewLiveClass.ClaUrl = it.ClaUrls
			}
		}
	}
	kmds, _ := (&SubSubjects{}).SubjectSIds(plays)
	for _, it := range kmds {
		for n, _ := range list {
			if list[n].SId == it.SId {
				list[n].SSId = it.Id
				list[n].SSName = it.Name
			}
		}
	}
	return err
}

type NewLiveByTime struct {
	NewLiveClass `xorm:"extends"`
	SaId         int64  `json:"s_id" xorm:"-"`
	SName        string `json:"s_name" xorm:"-"`
	SSId         int64  `json:"ss_id" xorm:"-"`
	SSName       string `json:"ss_name" xorm:"-"`
}

type LiveByTime struct {
	Id        int64  `json:"-" xorm:"cc_id"`
	LectureAt int64  `json:"lecture_at" xorm:"lecture_at"`
	TotalAt   string `json:"total_at" xorm:"total_at"`
}

func (this *LiveByTime) RecordTime_(uid int64, scIds []int64) ([]RecordAt, error) {
	list := []RecordAt{} // C++ new
	err := Db(0).Table("record").Cols("cc_id, lecture_at,total_at").
		Where(fmt.Sprintf("uid = %d ", uid)).
		In("cc_id", scIds).And("sign = 1").And("typ = 2").Find(&list)
	return list, err
}

func (this *NewLiveByTime) Playback(sid []int64, uid int64, val *Pager) error {
	list := make([]NewLiveByTime, 0)
	val.TName = "liveclass"
	val.Page--
	var field, sort string
	switch val.Coll {
	case 0:
		field = fmt.Sprintf("%s.lat", val.TName) // 排序
	default:
		field = fmt.Sprintf("%s.lat", val.TName) // 排序
	}
	//if 1 == val.Rules {
	//	sort = fmt.Sprintf("%s asc", field)
	//} else {
	sort = fmt.Sprintf("%s desc", field)
	//}
	swhere := fmt.Sprintf("states >= 2 ")
	val.Total, _ = Db(0).Table(val.TName).In("s_id", sid).Where(swhere).Where(val.ToWhere()).Count(this)
	err := Db(0).Table(val.TName).
		In("s_id", sid).
		Where(swhere).
		Where(val.ToWhere()).
		OrderBy(sort).
		Limit(val.Count, val.Page*val.Count).
		Find(&list)
	if err == nil {
		val.List = list
		//for i, row := range list {
		//	var sus Subjects
		//	list[i].SName, _ = sus.RecordClassName(row.SId)
		//	list[i].SSName, _ = sus.RecordClassNName(row.SId)
		//}
		//val.List = list
	}
	plays := []int64{}
	for n, _ := range list {
		plays = append(plays, list[n].NewLiveClass.SId)
	}
	// 从上面的 list 中 提取 课程Ids 通过in语句得到所有课程的名称
	//plys, _ := (&QqSName{}).RecordClassName(plays)
	plys, _ := (&Subjects{}).ReClassName(plays)
	for _, it := range plys {
		for n, _ := range list {
			if list[n].SId == it.SId {
				list[n].SaId = it.SId
				list[n].SName = it.SName
				list[n].ClaUrl = it.ClaUrls
				list[n].NewLiveClass.Years = int64(it.Yest)
			}
		}
	}
	kmds, _ := (&SubSubjects{}).SubjectSIds(plays)
	for _, it := range kmds {
		for n, _ := range list {
			if list[n].SId == it.SId {
				list[n].SSId = it.Id
				list[n].SSName = it.Name
			}
		}
	}
	scIds := make([]int64, 0, len(list))
	mapps := map[int64]*NewLiveClass{}
	for n, _ := range list {
		scIds = append(scIds, list[n].Id)
		mapps[list[n].Id] = &list[n].NewLiveClass
	}
	rects, err := (&LiveByTime{}).RecordTime_(uid, scIds)
	if err != nil {
		return err
	}
	for n, _ := range rects {
		mapps[rects[n].Id].Rect = []RecordAt{rects[n]}
	}
	return err
}

func (this *NewLiveOrdereds) OpenClassT(pid []string,ids []int64, val *Pager) error {
	list := make([]NewLiveOrdereds, 0)
	val.TName = "liveclass"
	val.Page--
	var field, sort string
	switch val.Coll {
	case 0:
		field = fmt.Sprintf("%s.lat", val.TName) // 排序
	default:
		field = fmt.Sprintf("%s.lat", val.TName) // 排序
	}
	if 1 == val.Rules {
		sort = fmt.Sprintf("%s asc", field)
	} else {
		sort = fmt.Sprintf("%s desc", field)
	}

	val.Total, _ = Db(0).Table(val.TName).Where(val.ToWhere()).In("pid", pid).
		NotIn("s_id",ids).
		Count(this)
	err := Db(0).Table(val.TName).
		Where(val.ToWhere()).
		In("pid", pid).
		NotIn("s_id",ids).
		OrderBy(sort).
		Limit(val.Count, val.Page*val.Count).
		Find(&list)
	if err == nil {
		val.List = list
	}
	// 这是课次的 list ， 取得 这些 课次的 课程名称 和 科目名称
	plays := []int64{}
	for n, _ := range list {
		plays = append(plays, list[n].NewLiveClass.SId)
	}
	// 从上面的 list 中 提取 课程Ids 通过in语句得到所有课程的名称
	plys, _ := (&QqSName{}).RecordClassName(plays)
	for _, it := range plys {
		for n, _ := range list {
			if list[n].SId == it.SId {
				list[n].SaId = it.SId
				list[n].SName = it.SName
				list[n].ClaUrl = it.ClaUrl
			}
		}
	}
	kmds, _ := (&SubSubjects{}).SubjectSIds(plays)
	for _, it := range kmds {
		for n, _ := range list {
			if list[n].SId == it.SId {
				list[n].SSId = it.Id
				list[n].SSName = it.Name
			}
		}
	}
	return err
}

type LiveCountName struct {
	Id    int64 `json:"s_id" xorm:"s_id"`       // s_id 	课程id
	Count int64 `json:"s_count" xorm:"s_count"` // count 课次数量
}

func (this *LiveCountName) LiveClassCount(sid []int64) ([]LiveCountName, error) {
	list := make([]LiveCountName, 0)
	err := Db(0).Table("liveclass").Select("s_id,COUNT(*) as s_count").In("s_id", sid).GroupBy("s_id").Find(&list)
	return list, err
}

type NewLiveOrdereds struct {
	NewLiveClass `xorm:"extends"`
	SaId         int64  `json:"s_id" xorm:"-"`
	SName        string `json:"s_name" xorm:"-"`
	SSId         int64  `json:"ss_id" xorm:"-"`
	SSName       string `json:"ss_name" xorm:"-"`
}

type QqSName struct {
	SId    int64  `json:"s_id" xorm:"id"`
	SName  string `json:"s_name" xorm:"name"`
}

//修改禁用课程不可展示
func (this *QqSName) RecordClassName(ids []int64) ([]QSName, error) {
	list := make([]QSName, 0)
	err := Db(0).Table("subject").Cols("id,name,course_url").In("id", ids).Find(&list)
	return list, err
}

type YesSName struct {
	SId     int64  `json:"s_id" xorm:"id"`
	SName   string `json:"s_name" xorm:"name"`
	Yest    int    `json:"s_yest" xorm:"year"`
	ClaUrls string `json:"cou_url" xorm:"course_url"`
}

func (this *Subjects) ReClassName(ids []int64) ([]YesSName, error) {
	list := make([]Subjects, 0)
	list1 := make([]YesSName, 0)
	err := Db(0).Table("subject").Cols("id,name,year,course_url").In("id", ids).Find(&list)
	for _, v := range list {
		var yes YesSName
		yes.SId = v.Id
		yes.SName = v.Name
		yes.Yest = v.Year
		yes.ClaUrls = v.ClassUrl
		list1 = append(list1, yes)
	}
	//fmt.Println(list1,"list1")
	return list1, err
}

type SubSubjects struct {
	SId  int64  `json:"ss_id"`              // 课程id
	Id   int64  `json:"s_id" xorm:"id"`     //科目id
	Name string `json:"s_nmae" xorm:"name"` //科目名称
}

func (this *SubSubjects) SubjectSIds(sil []int64) ([]SubSubjects, error) {

	list := make([]SubSubjects, 0)
	list1 := make([]SubSubjects, 0)
	newSli := make([]int64, 0)
	for _, v := range sil {
		newV := v - v%100000
		newSli = append(newSli, newV)
	}
	err := Db(0).Table("subject").Cols("id,name").In("id", newSli).Find(&list)
	if err != nil {
		return list, err
	}

	var newV int64
	for _, v := range sil {
		for _, i := range list {
			var val SubSubjects
			newV = v - v%100000
			if newV == i.Id {
				val.Id = i.Id
				val.SId = v
				val.Name = i.Name
			}
			list1 = append(list1, val)
		}
	}
	//fmt.Println("钢架的测试",list1)
	return list1, err
}


//公开课回放课次列表
func (this *NewLiveClass) OpenClassTS( ids []int64,val *Pager) error {
	list := make([]NewLiveClass, 0)
	val.TName = "liveclass"
	val.Page--
	var field, sort string
	switch val.Coll {
	case 0:
		field = fmt.Sprintf("%s.lat", val.TName) // 排序
	default:
		field = fmt.Sprintf("%s.lat", val.TName) // 排序
	}
	if 1 == val.Rules {
		sort = fmt.Sprintf("%s asc", field)
	} else {
		sort = fmt.Sprintf("%s desc", field)
	}
	var err error
	if len(ids) >= 1 {
		val.Total, _ = Db(0).Table(val.TName).Where(val.ToWhere()).NotIn("s_id",ids).Count(this)
		err = Db(0).Table(val.TName).
			Where(val.ToWhere()).
			NotIn("s_id",ids).
			OrderBy(sort).
			Limit(val.Count, val.Page*val.Count).
			Find(&list)
	}else{
		val.Total, _ = Db(0).Table(val.TName).Where(val.ToWhere()).Count(this)
		err = Db(0).Table(val.TName).
			Where(val.ToWhere()).
			OrderBy(sort).
			Limit(val.Count, val.Page*val.Count).
			Find(&list)
	}
	if err == nil {
		val.List = list
	}
	return err
}